package com.tij.rtti.typeinfo.pet;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName:ch 14-3-2 p329
 * @author:
 * @Description: TODO
 * data:2024/10/7 7:10
 * @since
 **/
public class PetCount3 {

    static class PetCounter extends LinkedHashMap<Class<? extends Pet>,Integer> {
        private static final HashMap<Class<? extends Pet>, Integer> petMap ;

        static {
            petMap = new HashMap<Class<? extends Pet>,Integer>();
            for (Class<? extends Pet> c : LiteralPetCreator.allTypes) {
                petMap.put(c, 0);
            }
        }
        public PetCounter(){
            // 初始化一个空的map   有没有一个方法直接将list 转为map
            super(petMap);
        }

        public void count(Pet pet){
            // class is instance() eliminates instanceofs
            for(Map.Entry<Class<? extends Pet>, Integer> pair: entrySet()){
                if(pair.getKey().isInstance(pet)){
                    put(pair.getKey(), pair.getValue()+1);
                }
            }
        }

        public String toString(){
            StringBuilder result = new StringBuilder("{");
            for(Map.Entry<Class<? extends Pet>,Integer> pair: entrySet()){
                result.append(pair.getKey().getSimpleName());
                result.append("=");
                result.append(pair.getValue());
                result.append(", ");
            }
            //result.delete(result.length()-2,result.length());
            result.append("}");

            return result.toString();
        }

        public static void main(String[] args) {
            PetCounter petCount = new PetCounter();
            for(Pet pet:Pets.createArray(20)){
                System.out.print(pet.getClass().getSimpleName() + " ");
                petCount.count(pet);
            }

            System.out.println();
            System.out.println(petCount);
        }
    }
}
